package com.nxy.cpfsfe;

import com.adtec.starring.data.ibatis.IBaseDos;
import com.adtec.starring.data.route.IDataSourceRoute;
import com.adtec.starring.datapool.EPOper;
import com.adtec.starring.exception.BaseException;
import com.adtec.starring.global.SysDef;
import com.adtec.starring.log.TrcLog;
import com.adtec.starring.respool.PoolOperate;
import com.adtec.starring.respool.ResPool;
import com.adtec.starring.respool.SystemParameter;
import com.adtec.starring.respool.spring.LoadSpringFile;
import com.adtec.starring.struct.data.Sql;
import com.adtec.starring.struct.dta.DtaInfo;
import com.adtec.starring.struct.svcdepend.SvcDepend;
import com.adtec.starring.tool.DTATool;
import com.adtec.starring.util.Encry;
import com.adtec.starring.util.SpringUtil;
import com.adtec.starring.util.StringTool;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nxy.cpfsfe.config.CpfsFeAllConfig;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class RedisOper {

	/**
	 * 平台加密方法
	 */
	public String encryString(String passwd) {
		passwd = Encry.encryString(passwd);
		return passwd;
	}
	
	/**
	 * 平台解密方法
	 */
	public String decryptString(String passwd) {
		passwd = Encry.decryptString(passwd);
		return passwd;
	}
	
	/**
	 * 加载客户化SpringXML文件
	 */
	public void loadSpringXMLNoPasswd(String fileName) {
		String fileFullName = SysDef.WORK_DIR + SysDef.FILE_SP + SystemParameter.ETC_PATH + SysDef.FILE_SP + fileName;
		File file = new File(fileFullName);
		if (file.exists()) {
			LoadSpringFile loadSpring = (LoadSpringFile) SpringUtil.getBean("loadSpring");
			loadSpring.loadSpringFile(fileFullName);
		}

	}

	public void init(){
		TrcLog.log("RedisOper.log", "init.................");
		loadSpringXML("spring-redis.xml");
		loadTHDXML("thd_provider1.xml");
	}
	
	public void initThd1(){
		TrcLog.log("RedisOper.log", "initThd1.................");
		loadTHDXML("thd_provider1.xml");
	}
	/**
	 * 加载客户化thd文件，
	 */
	public void loadTHDXML(String fileName) {
		String fileFullName = SysDef.WORK_DIR + SysDef.FILE_SP + SystemParameter.ETC_PATH + SysDef.FILE_SP + fileName;
		TrcLog.log("RedisOper.log" ,"加载redis配置文件\nredis配置文件路径: " + fileFullName);
		File file = new File(fileFullName);
		// File file = new File(fileName);
		String fileFullStr = "";
		String passwd = "";
		String passwdNew = "";
		InputStream fis = null;
		if (file.exists()) {

			try {
				fis = new FileInputStream(file);
				int len = 0;
				byte[] buf = new byte[8192];
				while ((len = fis.read(buf)) != -1) {
					fileFullStr = new String(buf, 0, len);
				}

			} catch (Exception e1) {
				throw new BaseException("PCA1006", "加载客户化SpringXML文件失败！");
			} finally {
				try {
					if (fis != null) {
						fis.close();
					}
				} catch (IOException e) {
					Logable._error(e);
				}
			}

			// System.out.println("fileFullStr " + fileFullStr);

			// String passwd1 = "Redis_2018@@";//BO2Fapr5m0Rdv36IZYXz9w==
			// passwd1 = Encry.encryString(passwd1);
			// System.out.println("encryString " +passwd1);
			// passwd1 = Encry.decryptString(passwd1);
			// System.out.println("decryptString " +passwd1);
			// <constructor-arg index="4" value="
			if (fileFullStr.equals("")) {
				throw new BaseException("PCA1006", "加载客户化SpringXML文件失败！");
			}

		

			
			//if(!StringTool.isNullOrEmpty(passwd) && !StringTool.isNullOrEmpty(passwdNew)) {
			//add by chenao 
			/*if(!StringTool.isNullOrEmpty(passwd)){
    			TrcLog.log("RedisOper.log", "passwd " + passwd);
    			passwdNew = Encry.decryptString(passwd);
    			TrcLog.log("RedisOper.log", "passwdNew " + passwdNew);
    
    			fileFullStr = fileFullStr.replace(passwd, passwdNew);
			}*/
			// System.out.println(fileFullStr);
			TrcLog.log("RedisOper.log", fileFullStr);
			try { 
    			LoadSpringFile loadSpring = (LoadSpringFile) SpringUtil.getBean("loadSpring");
    			// loadSpring.loadSpringFile(fileFullName);
    			loadSpring.loadSpringFileString(fileFullStr);
    			//SpringUtil.getBean("redisCluster");
			} catch (Exception e) {
			    Logable._error(e);
			}
		}

	}
	
	/**
	 * 加载客户化SpringXML文件，
	 */
	public void loadSpringXML(String fileName) {
		String fileFullName = SysDef.WORK_DIR + SysDef.FILE_SP + SystemParameter.ETC_PATH + SysDef.FILE_SP + fileName;
		TrcLog.log("RedisOper.log" ,"加载redis配置文件\nredis配置文件路径: " + fileFullName);
		File file = new File(fileFullName);
		// File file = new File(fileName);
		String fileFullStr = "";
		String passwd = "";
		String passwdNew = "";
		InputStream fis = null;
		if (file.exists()) {

			try {
				fis = new FileInputStream(file);
				int len = 0;
				byte[] buf = new byte[8192];
				while ((len = fis.read(buf)) != -1) {
					fileFullStr = new String(buf, 0, len);
				}

			} catch (Exception e1) {
				throw new BaseException("PCA1006", "加载客户化SpringXML文件失败！");
			} finally {
				try {
					if (fis != null) {
						fis.close();
					}
				} catch (IOException e) {
					Logable._error(e);
				}
			}

			// System.out.println("fileFullStr " + fileFullStr);

			// String passwd1 = "Redis_2018@@";//BO2Fapr5m0Rdv36IZYXz9w==
			// passwd1 = Encry.encryString(passwd1);
			// System.out.println("encryString " +passwd1);
			// passwd1 = Encry.decryptString(passwd1);
			// System.out.println("decryptString " +passwd1);
			// <constructor-arg index="4" value="
			if (fileFullStr.equals("")) {
				throw new BaseException("PCA1006", "加载客户化SpringXML文件失败！");
			}

			try {
				fis = new FileInputStream(file);
			} catch (Exception e1) {
				try {
					if (fis != null) {
						fis.close();
					}
				} catch (IOException e) {
				    Logable._error(e);
					throw new BaseException("PCA1006", "加载客户化SpringXML文件失败！");
				}
				throw new BaseException("PCA1006", "加载客户化SpringXML文件失败！");
			}

			SAXReader reader = new SAXReader();
			try {
				reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
				Document doc = null;
				doc = reader.read(fis);

				/** 读取根节点 */
				Element list = doc.getRootElement();
				/** list节点放到Iterator里处理 */
				Iterator<?> bean = list.elementIterator("bean");
				// 外层记录数
				int i = 0;
				// 遍历所有bean节点
				for (; bean.hasNext(); i++) {
					Element beansElement = (Element) bean.next();
					String id = beansElement.attributeValue("id");
					if (id.equals("redisCluster")) {
						Iterator<?> arg = beansElement.elementIterator("constructor-arg");
						int j = 0;

						// 遍历所有constructor-arg节点
						for (; arg.hasNext(); j++) {
							Element argElement = (Element) arg.next();
							String index = argElement.attributeValue("index");
							if (index.equals("4")) {
								passwd = argElement.attributeValue("value");
								break;
							}
						}
					}
				}
			} catch (Exception e) {
			    Logable._error(e);
			    if(e instanceof BaseException)
			        throw (BaseException) e;
			    else
			        throw new BaseException("PCA1006", e, "加载客户化SpringXML文件失败！");
			} finally {
				try {
					if (fis != null) {
						fis.close();
					}
				} catch (IOException e) {
				    Logable._error(e);
				}
			}
			//if(!StringTool.isNullOrEmpty(passwd) && !StringTool.isNullOrEmpty(passwdNew)) {
			//add by chenao 
			if(!StringTool.isNullOrEmpty(passwd)){
    			TrcLog.log("RedisOper.log", "passwd " + passwd);
    			passwdNew = Encry.decryptString(passwd);
    			TrcLog.log("RedisOper.log", "passwdNew " + passwdNew);
    
    			fileFullStr = fileFullStr.replace(passwd, passwdNew);
			}
			// System.out.println(fileFullStr);
			TrcLog.log("RedisOper.log", fileFullStr);
			try { 
    			LoadSpringFile loadSpring = (LoadSpringFile) SpringUtil.getBean("loadSpring");
    			// loadSpring.loadSpringFile(fileFullName);
    			loadSpring.loadSpringFileString(fileFullStr);
    			SpringUtil.getBean("redisCluster");
			} catch (Exception e) {
			    Logable._error(e);
			}
		}

	}

	public static void main(String[] args) {
		RedisOper redisOper = new RedisOper();
		redisOper.loadSpringXML("f:\\spring-redis.xml");
	}
    
    /**
     * 新增map 
     * 
     * @param key
     * @param field
     * @param value
     */

    public void saveHash(String field, String value) {
        // jc.setex( field, 1296000,value);
        CpfsFeAllConfig.jedisCluster.setex(field, Integer.parseInt(ResPool.configMap.get("time_out")), value);
        // ResPool.configMap对应平台配置文件etc/config.zh_cn.utf8.properties，ResPool.configMap.get("time_out")
        // 从etc/config.zh_cn.utf8.properties取"time_out"的值。
    }

    /**
     * 查询map
     * 
     * @param key
     * @param field
     */
    public String findHash(String key) {
        TrcLog.log("jedistime.log", "findHashBegin");
        TrcLog.log("jedistime.log", "hgetBegin");
        String value = CpfsFeAllConfig.jedisCluster.get(key);
        // jc.expire( key, 1296000);
        CpfsFeAllConfig.jedisCluster.expire(key, Integer.parseInt(ResPool.configMap.get("time_out")));

        TrcLog.log("jedistime.log", "findHashover");
        return value;
    }
    
    /**
     * 
     * @author chenao
     * @param key
     * @param field
     * @param value
     */
    public static void saveUsrMap() {
        DtaInfo dtaInfo = DtaInfo.getInstance();
        // CompSDO compSDOs = (CompSDO) EPOper.getCompSDO(dtaInfo.getTpId(),
        // "ReqBean.head");
        String appBrchNo = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.servInitrBrch");
        String chnlNo = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.servInitrChanl");
        String ip = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.iPAddr");
        String mac = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.macAddr");
        String eqpSerNo = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.eqpSerNo");
        String usrId = (String) EPOper.get(dtaInfo.getTpId(), "c04LgnSrv_output0.usrId");
        TrcLog.info("redis.log", "begin 用户id %s", usrId);
        String usrKey = usrId + "_" + chnlNo;
        CpfsFeAllConfig.jedisCluster.hset(usrKey, "appBrchNo", appBrchNo);
        CpfsFeAllConfig.jedisCluster.hset(usrKey, "ip", ip);
        CpfsFeAllConfig.jedisCluster.hset(usrKey, "mac", mac);
        CpfsFeAllConfig.jedisCluster.hset(usrKey, "eqpSerNo", eqpSerNo);
        CpfsFeAllConfig.jedisCluster.hset(usrKey, "chnlNo", chnlNo);
        CpfsFeAllConfig.jedisCluster.expire(usrKey, 120);
        boolean flag = CpfsFeAllConfig.jedisCluster.exists(usrKey);
        if (flag == true) {
            TrcLog.info("redis.log", "end true 用户id %s", usrKey);
        } else {
            TrcLog.info("redis.log", "end false 用户id %s", usrKey);
        }
        // sb.append((String) compSDOs.getValue("usrId"));
        // sb.append((String) compSDOs.getValue("eqpNo"));
        // sb.append((String) compSDOs.getValue("servTypCd"));
        // String str = sb.toString();
        // JedisCluster jc = (JedisCluster) SpringUtil.getBean("redisCluster");
        // jc.setex(str,Integer.parseInt(ResPool.configMap.get("redis_randomfactor")),str1);

    }

    public static void removeUsrMap() {
        DtaInfo dtaInfo = DtaInfo.getInstance();
        String usrId = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.usrId");
        String chnlNo = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.servInitrChanl");
        String usrKey = usrId + "_" + chnlNo;
        CpfsFeAllConfig.jedisCluster.del(usrKey);
    }

    public static void getUsrMap() {
        DtaInfo dtaInfo = DtaInfo.getInstance();
        String appBrchNo = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.servInitrBrch");
        String chnlNo = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.servInitrChanl");
        String ip = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.iPAddr");
        String mac = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.macAddr");
        String eqpSerNo = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.eqpSerNo");
        String usrId = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.usrId");
        String usrKey = usrId + "_" + chnlNo;
        boolean flag = CpfsFeAllConfig.jedisCluster.exists(usrKey);
        if (flag == false) {
            throw new BaseException("PC01100");// 用户未登录；
        }

        String chnlNo0 = CpfsFeAllConfig.jedisCluster.hget(usrKey, "chnlNo");
        if (!chnlNo0.equals(chnlNo)) {
            throw new BaseException("PC01105");// 渠道号不一致；
        }

        String appBrchNo0 = CpfsFeAllConfig.jedisCluster.hget(usrKey, "appBrchNo");
        if (!appBrchNo0.equals(appBrchNo))
            throw new BaseException("PC01101");// 应用机构号不一致；

        String ip0 = CpfsFeAllConfig.jedisCluster.hget(usrKey, "ip");
        if (!ip0.equals(ip))
            throw new BaseException("PC01102");// IP不一致；

        String mac0 = CpfsFeAllConfig.jedisCluster.hget(usrKey, "mac");
        if (!mac0.equals(mac))
            throw new BaseException("PC01103");// MAC不一致；

        String eqpSerNo0 = CpfsFeAllConfig.jedisCluster.hget(usrKey, "eqpSerNo");
        if (!eqpSerNo0.equals(eqpSerNo))
            throw new BaseException("PC01104");// 设备序列号不一致；

        CpfsFeAllConfig.jedisCluster.expire(usrKey, 120);
    }

    public static String qryBindEqpCount() {
        return "1";
    }

    public static String getRandomFactor() {
        // DtaInfo dtaInfo = DtaInfo.getInstance();

        // 获取输入参数
        StringBuffer sb = new StringBuffer();
        // CompSDO compSDOs = (CompSDO) EPOper.getCompSDO(dtaInfo.getTpId(),
        // "s04DbOpAddCertInfo_input");
        // sb.append((String) compSDOs.getValue("servTypCd"));
        sb.append(UUID.randomUUID());
        // sb.append((String) compSDOs.getValue("usrId"));
        // 取加密后的结果
        MessageDigest md = null;
        String inptSmsCptcNoString = null;
        try {
            md = MessageDigest.getInstance("md5");
            byte[] bs = md.digest(sb.toString().getBytes());
            inptSmsCptcNoString = new BASE64Encoder().encode(bs);
            return inptSmsCptcNoString;
        } catch (NoSuchAlgorithmException e1) {
            throw new BaseException("生成随机因子失败");
        }

    }

    /**
     * 
     * @author chenao
     * @param key
     * @param field
     * @param value
     */
    public static String saveRanFctr(String usrId, String servCd) {
        // DtaInfo dtaInfo = DtaInfo.getInstance();
        // CompSDO compSDOs = (CompSDO) EPOper.getCompSDO(dtaInfo.getTpId(),
        // "ReqBean.head");
        String key = usrId + servCd;
        String value = getRandomFactor();
        CpfsFeAllConfig.jedisCluster.set(key, value);
        CpfsFeAllConfig.jedisCluster.expire(key, 300);
        boolean flag = CpfsFeAllConfig.jedisCluster.exists(key);
        if (flag == true) {
            TrcLog.info("redis.log", "用户id:%s  velue:%s", key, value);
        }
        return value;
        // sb.append((String) compSDOs.getValue("usrId"));
        // sb.append((String) compSDOs.getValue("eqpNo"));
        // sb.append((String) compSDOs.getValue("servTypCd"));
        // String str = sb.toString();
        // JedisCluster jc = (JedisCluster) SpringUtil.getBean("redisCluster");
        // jc.setex(str,Integer.parseInt(ResPool.configMap.get("redis_randomfactor")),str1);

    }

    /**
     * 
     * @author chenao
     * @param key
     * @param field
     * @param value
     */
    public static String getRanFctr(String usrId, String servCd) {
        // DtaInfo dtaInfo = DtaInfo.getInstance();
        // CompSDO compSDOs = (CompSDO) EPOper.getCompSDO(dtaInfo.getTpId(),
        // "ReqBean.head");
        String key = usrId + servCd;
        boolean flag = CpfsFeAllConfig.jedisCluster.exists(key);
        if (flag == true) {
            TrcLog.info("redis.log", "获取用户key: %s ,ranFctr：%s", key, CpfsFeAllConfig.jedisCluster.get(key));
            return CpfsFeAllConfig.jedisCluster.get(key);
        } else {
            return "";
        }
        // jc.expire(key, 300);

    }

    public static boolean exaRanFctr(String usrId, String servCd, String ranFctr) {
        String redis_ran = getRanFctr(usrId, servCd);
        TrcLog.info("redis.log", "redis:%s  ranFctr:%s", redis_ran, ranFctr);
        if (ranFctr.equals(redis_ran)) {
            return true;
        }
        return false;
    }

    public static final String DS_ROUAT_BEAN_NAME = "dsRoute";// 数据库路由Bean名称
    public static final String DB_DOMAIN_NAME     = "";       // 数据域名称

    public static void putParamRedis() {
        putChnlRedis();
        putSrvRedis();
        putTypTmplToRedis();
    }

    /**
     * @author chenao
    * 将渠道参数存入redis缓存
    */
    public static void putChnlRedis() {
        String tpId = DtaInfo.getInstance().getTpId();
        // 加载redis配置文件
        IDataSourceRoute dsRoute = (IDataSourceRoute) SpringUtil.getBean(RedisOper.DS_ROUAT_BEAN_NAME);
        IBaseDos baseDos = dsRoute.getBaseDos(RedisOper.DB_DOMAIN_NAME);
        String parmSql = "select ASSC_O_ECD,CHNL_CD,UNFY_CHNL from TR_UNFY_CHNL LIMIT 0,999999";
        int num = baseDos.executeSql(Sql.SELLIST, parmSql, "TR_UNFY_CHNL");
        for (int i = 0; i < num; i++) {
            String key = (String) EPOper.get(tpId, "TR_UNFY_CHNL[" + i + "].ASSC_O_ECD") + "_" + (String) EPOper.get(tpId, "TR_UNFY_CHNL[" + i + "].CHNL_CD") + "_" + "TR_UNFY_CHNL";

            String val = (String) EPOper.get(tpId, "TR_UNFY_CHNL[" + i + "].UNFY_CHNL");

            String string = CpfsFeAllConfig.jedisCluster.set(key, val);
            TrcLog.log("redis.log", key + ":" + val);
        }
    }

    /***
     * @author chenao    
     * @param asscOEcd
     * @param chnlCd
     * @return  unfyChnl
     */
    public static String getChnlRedis(String asscOEcd, String chnlCd) {
        String key = asscOEcd + "_" + chnlCd + "_" + "TR_UNFY_CHNL";
        String unfyChnl = CpfsFeAllConfig.jedisCluster.get(key);
        TrcLog.log("redis.log", "统一渠道：" + key + ":" + unfyChnl);
        if (unfyChnl == null || unfyChnl == "") {
            putChnlRedis();
            unfyChnl = CpfsFeAllConfig.jedisCluster.get(asscOEcd + "_" + chnlCd + "_" + "TR_UNFY_CHNL");
        }
        return unfyChnl;
    }

    /**
     * @author chenao
     * 将服务参数存入redis缓存       
     */
    public static void putSrvRedis() {          
        String tpId = DtaInfo.getInstance().getTpId();
        // 加载redis配置文件
        IDataSourceRoute dsRoute = (IDataSourceRoute) SpringUtil.getBean(RedisOper.DS_ROUAT_BEAN_NAME);
        IBaseDos baseDos = dsRoute.getBaseDos(RedisOper.DB_DOMAIN_NAME);
        String parmSql = "select ASSC_O_ECD,CHNL_CD,SRV_CD,AUTH_CD,SIGN_FLD,CHK_FLD,ADD_FLG,SRV_NAME from TR_TRAN_AUTH LIMIT 0,999999";
        int num = baseDos.executeSql(Sql.SELLIST, parmSql, "TR_TRAN_AUTH"); 
        TrcLog.log("redis.log",  "SrvRedis-num:" + num); 
        for (int i = 0; i < num; i++) {
            String key = (String) EPOper.get(tpId, "TR_TRAN_AUTH[" + i + "].ASSC_O_ECD") + "_" + (String) EPOper.get(tpId, "TR_TRAN_AUTH[" + i + "].CHNL_CD") + "_" + (String) EPOper.get(tpId, "TR_TRAN_AUTH[" + i + "].SRV_CD") + "_" + "TR_TRAN_AUTH";

            String authCd = (String) EPOper.get(tpId, "TR_TRAN_AUTH[" + i + "].AUTH_CD");
            String chkFld = (String) EPOper.get(tpId, "TR_TRAN_AUTH[" + i + "].CHK_FLD");
            String signFld = (String) EPOper.get(tpId, "TR_TRAN_AUTH[" + i + "].SIGN_FLD");
            String addFlg = (String) EPOper.get(tpId, "TR_TRAN_AUTH[" + i + "].ADD_FLG");
            String srvName = (String) EPOper.get(tpId, "TR_TRAN_AUTH[" + i + "].SRV_NAME");
            if(chkFld== null) {
            	chkFld = "";
            }
            if(signFld== null) {
            	signFld = "";
            } 
            if(addFlg==null){
            	addFlg="";
            }
            if(srvName==null){
            	srvName="";
            }
            Map<String,String> redisMap = new HashMap<String,String>();
            redisMap.put("AUTH_CD", authCd);
            redisMap.put("CHK_FLD", chkFld);
            redisMap.put("SIGN_FLD", signFld);
            redisMap.put("ADD_FLG", addFlg);
            redisMap.put("SRV_NAME", srvName);
            
            String string = CpfsFeAllConfig.jedisCluster.hmset(key, redisMap);
            
            TrcLog.log("redis.log", key + ":" + string+"---存入内容："+redisMap.toString());
        }
    }
    /***
     * 
     * @param __random 需前端上传上次请求的随机数 【数据对象形式】例如：ReqBean.head.sessId
     * @param servEcd 需要匹配的服务码
     * @return Boolean
     */
    public static boolean examAvlGrpCert(String __random,String servEcd){
    	 String tpId = DtaInfo.getInstance().getTpId();
         // 加载redis配置文件
         String random = (String) EPOper.get(tpId, __random);
         String certTypNo = (String) EPOper.get(tpId, "ReqBean.head.certTypNo");
         String key = random+"_"+servEcd+"_"+"AVLGRP";
         List<String> list = CpfsFeAllConfig.jedisCluster.lrange(key, 0, -1);
         for(int i = 0;i < list.size();i++) {
        	 String value = list.get(i);
        	 if(certTypNo.equals(value)) {
                 CpfsFeAllConfig.jedisCluster.del(key);
        		 return true;
        	 }
         }
    	return false;
    }
    
    
    /***
     * 半穿透用校验用户可用认证
     * @param random 随机因子
     * @param servEcd 需要匹配的服务码
     * @return Boolean
     */
    public static boolean examAvlGrpCertForHP(String ranFac,String servEcd,String certTypNo){
         
         // 加载redis配置文件
         String key = ranFac+"_"+servEcd+"_"+"AVLGRP";
         List<String> list = CpfsFeAllConfig.jedisCluster.lrange(key, 0, -1);
         for(int i = 0;i < list.size();i++) {
             String value = list.get(i);
             if(certTypNo.equals(value)) {
                 return true;
             }
         }
        return false;
    }
    
    
    
    
    
    
  
//    /***
//     * @author chenao
//     * 公共校验
//     */
//    public static void pubExam(){
//    	DtaInfo dtaInfo = DtaInfo.getInstance();
//		String asscOEcd = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.servInitrBrch");
//		String chnlCd = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.servInitrChanl"); 
//		String srv = (String) EPOper.get(dtaInfo.getTpId(), "ReqBean.head.servEcd");
//		String authCd = getSrvRedis(asscOEcd, chnlCd, srv);
//		if(authCd==null || authCd ==""){
//			throw new BaseException("PCA1006", "没有权限");
//		}
//		for(int i = 0; i < 3 ; i++){
//			String am = getCharAt(authCd, 1);
//			if(am.equals("1")){
//				switch (i) {
//				case  0:
//					//判断是否登录
//					RedisLgnInfo lgnInfo = new RedisLgnInfo();
//					lgnInfo.getUsrInfo();
//					break;
//				case 1:
//					//判断是否需要同步授权
//					PubBean.qSynAuthChk();
//					break;
//				case 2:
//					//判断是否需要校验取款密码
//					PubBean.examPwd();
//					break;
//				default:
//					break;
//				}
//			}
//			
//		}
//		
//    }

//    public static String getCharAt(String str, int position) {
//        int length = str.length();
//        String f = "";
//        if (position > length) {
//            int n = position - length;
//            f = "%0" + n + "d";
//            f = String.format(f, 0);
//        }
//        str = str + f;
//        System.out.println(str);
//        String str1 = String.valueOf(str.charAt(position - 1));
//        return str1;
//    }

    /**
     * 获取报文头中认证类型为04指纹的认证内容
     * "04": {"certCntnt":"wuerklsf2131"}
     * @return
     */
    public static String getFingerprintsCertCntnt() {
        String headCertCntnt = (String) EPOper.get(DtaInfo.getInstance().getTpId(), "ReqBean[0].head[0].certCntnt");

        ObjectMapper mapper = new ObjectMapper();
        try {
            Map<String, Object> map = mapper.readValue(headCertCntnt, Map.class);
            Map<String, String> map1 = (Map<String, String>) map.get("04");
            if (map == null || map1.isEmpty()) {
                throw new BaseException("PCA1106", "未上送指纹密码");
            }

            String certCntnt = map1.get("certCntnt");

            return certCntnt;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("PCA1106", "未上送指纹密码");
        }
    }

    
    /**
     * 获取流水
     * @param key 键值
     * @param qty 流水最大值
     * @return 流水值
     */
    public static long getSeq(String key, long qty) {
        if(qty < 2)
            return 1;
        Long seq = CpfsFeAllConfig.jedisCluster.incr(key);
        if (seq > qty || seq < 1) {
            CpfsFeAllConfig.jedisCluster.set(key, "1");
            return 1;
        }
        return seq;
    }
    
    public static String getInitrSeqNo() {
        long seq = getSeq("InitrSeqNo", 9999999);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return String.format("%s%08d", sdf.format(new Date()), seq);
    }
    
    public static String getRlSerNO(String parm) {
        int seq = (int) (CpfsFeAllConfig.jedisCluster.incr(parm) % 100000);
        DtaInfo dtaInfo = DtaInfo.getInstance();
        String nodeName = dtaInfo.getNodeName(); // 取机器节点号
		int nodeNo = Integer.parseInt(nodeName); // 转化为整型的节点号
        return String.format("%03d%05d", nodeNo, seq);
    }
    /**
	 *从Redis中取汇路顺序 ,若Redis中不存在，则取数据库中数据，并存Redis
	 */
	public void getValueFromRedis() {
		String tpId=DtaInfo.getInstance().getTpId();
		
        IDataSourceRoute dsRoute = (IDataSourceRoute) SpringUtil.getBean(RedisOper.DS_ROUAT_BEAN_NAME);
        IBaseDos baseDos = dsRoute.getBaseDos(RedisOper.DB_DOMAIN_NAME);

		String sql = "SELECT PARM_ACTL_VAL,ASSC_O_ECD,LV_CD FROM tp_parm WHERE PARM_TYP_CD='3020' AND DSP_SER_NO='1'";

		int num = baseDos.executeSql(Sql.SELLIST, sql, "TP_PARM");

		String key = "";
		if (num <= 0) {// 参数表中不存在该机构的汇路
			throw new BaseException("SPUB004", "该机构的汇路不存在");
		} else {
			for (int i = 0; i < num; i++) {
				key=(String)EPOper.get(tpId, "TP_PARM["+i+"].ASSC_O_ECD")+"_"+
						(String)EPOper.get(tpId, "TP_PARM["+i+"].LV_CD")+"_rmChnl";
                CpfsFeAllConfig.jedisCluster.set(key, (String)EPOper.get(tpId, "TP_PARM["+i+"].PARM_ACTL_VAL"));
			}
		}			
	}
	/**
	 * 获取用户信息
	 */
	public static HashMap<String,UsrInfo> getTelrInfo(String usrId,String chnlNo) {
		boolean usrIdFlag = CpfsFeAllConfig.jedisCluster.exists(usrId + "-" + chnlNo);
		//不存在登录信息
		if(usrIdFlag == false) {
		    throw new BaseException("PCA1006", "用户登录信息不存在或已失效，请先进行登录");
		}
		String lgnByte = CpfsFeAllConfig.jedisCluster.get(usrId + "-" + chnlNo);
		if (StringTool.isNullOrEmpty(lgnByte)) {
			throw new BaseException("PCA1006", "用户登录信息不存在,请重新登录");
		}
		Map<String, UsrInfo> usrMap = new HashMap<>();
		@SuppressWarnings("unchecked")
		Map<String, ?> tempUsrMap = JSON.parseObject(lgnByte, Map.class);
		for (Map.Entry<String, ?> entry : tempUsrMap.entrySet()) {
			String key = entry.getKey();
			Object value = entry.getValue();
			if (value instanceof Map) {
				String usrLgnInfo = JSON.toJSONString(value);
				UsrInfo usrInfo = JSON.parseObject(usrLgnInfo, UsrInfo.class);
				 usrMap.put(key, usrInfo);
			} 
		}
		return (HashMap<String, UsrInfo>) usrMap;
	}
	
	
	/**
     * 获取服务权限控制数据
     */
	public static Map<String,String> getSrvRedis(String asscOEcd, String chnlCd, String srv) {
        String key1 = asscOEcd + "_" + chnlCd + "_" + srv + "_TR_TRAN_AUTH";
        TrcLog.info("PubExam.log", key1);
        Map<String,String> auth = CpfsFeAllConfig.jedisCluster.hgetAll(key1);
       
        if (auth.get("AUTH_CD")==null || auth.get("AUTH_CD")=="") {
            //RedisOper.putSrvRedis();
        	//添加服务依赖
        	SvcDepend svcDepend = new SvcDepend();
    		svcDepend.setSrcType("C");
    		DtaInfo dtaInfo = DtaInfo.getInstance();
    		String dtaNm = dtaInfo.getDtaName();
    		String svcNm = dtaInfo.getSvcName();
    		TrcLog.info("PubBean.log", dtaNm + ":" + svcNm);
    		svcDepend.setSrcName(dtaNm);
    		svcDepend.setSrcSvcName(svcNm);
    		String destType = "O";
    		String destName = "c00_w01_output";
    		String svcName = "putRedisSrv";
    		svcDepend.setDestType(destType);
    		svcDepend.setDestName(destName);
    		svcDepend.setSvcName(svcName);
    		ConcurrentHashMap<String, SvcDepend> svcDependMap = PoolOperate.getResPoolByVersion(dtaInfo.getDepVersion())
    				.getAlaHashMap().get(dtaInfo.getDtaName()).getSvcDependMap();
    		String key = dtaNm + svcNm + destName + svcName;
    		if (svcDependMap.get(key) == null) {
    			svcDependMap.put(key, svcDepend);
    		}
    		EPOper.put(dtaInfo.getTpId(), "ReqBean[0].head[0].servEcd[0]", "putRedisSrv");
    		DTATool dtaTool = (DTATool) SpringUtil.getBean("dtaTool");
			dtaTool.callOutPut("c00_w01_output", "putRedisSrv");
			TrcLog.info("PubExam.log", "调用%s的%s","c00_w01_output","putRedisSrv");
			
			TrcLog.info("PubExam.log", auth.toString()+"--");
        }
        return auth;
    }
	
	
	/**
     * @author gongxb
     * 将类型转换模板数据存入缓存
     */
    public static void putTypTmplToRedis() {        
        String tpId = DtaInfo.getInstance().getTpId();
        // 加载redis配置文件
        IDataSourceRoute dsRoute = (IDataSourceRoute) SpringUtil.getBean(RedisOper.DS_ROUAT_BEAN_NAME);
        IBaseDos baseDos = dsRoute.getBaseDos(RedisOper.DB_DOMAIN_NAME);
        String parmSql = "select ASSC_O_ECD,MAJTYP_CD,MNRTYP_CD,TRANS_MNRTYP_CD,TMP1,TMP2,TMP3,TMP4 from TP_TYP_TMPL LIMIT 0,999999";
        int num = baseDos.executeSql(Sql.SELLIST, parmSql, "TP_TYP_TMPL"); 
        TrcLog.log("redisTypTmpl.log",  "TmplRedis-num:" + num); 
        for (int i = 0; i < num; i++) {
            String key = (String) EPOper.get(tpId, "TP_TYP_TMPL[" + i + "].ASSC_O_ECD") + "_" + (String) EPOper.get(tpId, "TP_TYP_TMPL[" + i + "].MAJTYP_CD") + "_" + (String) EPOper.get(tpId, "TP_TYP_TMPL[" + i + "].MNRTYP_CD") + "_" + "TP_TYP_TMPL";

            String asscOEcd = (String) EPOper.get(tpId, "TP_TYP_TMPL[" + i + "].ASSC_O_ECD");
            String majTypCd = (String) EPOper.get(tpId, "TP_TYP_TMPL[" + i + "].MAJTYP_CD");
            String mnrTypCd = (String) EPOper.get(tpId, "TP_TYP_TMPL[" + i + "].MNRTYP_CD");
            String transMnrTypCd = (String) EPOper.get(tpId, "TP_TYP_TMPL[" + i + "].TRANS_MNRTYP_CD");
            String tmp1 = (String) EPOper.get(tpId, "TP_TYP_TMPL[" + i + "].TMP1");
            String tmp2 = (String) EPOper.get(tpId, "TP_TYP_TMPL[" + i + "].TMP2");
            String tmp3 = (String) EPOper.get(tpId, "TP_TYP_TMPL[" + i + "].TMP3");
            String tmp4 = (String) EPOper.get(tpId, "TP_TYP_TMPL[" + i + "].TMP4");
            
            if(asscOEcd== null) {
                asscOEcd = "";
            }
            if(majTypCd== null) {
                majTypCd = "";
            } 
            if(mnrTypCd== null) {
                mnrTypCd = "";
            } 
            if(transMnrTypCd== null) {
                transMnrTypCd = "";
            } 
            if(tmp1== null) {
                tmp1 = "";
            } 
            if(tmp2== null) {
                tmp2 = "";
            } 
            if(tmp3== null) {
                tmp3 = "";
            } 
            if(tmp4== null) {
                tmp4 = "";
            } 
            
            
            Map<String,String> typTmplMap = new HashMap<String,String>();
            typTmplMap.put("ASSC_O_ECD", asscOEcd);
            typTmplMap.put("MAJTYP_CD", majTypCd);
            typTmplMap.put("MNRTYP_CD", mnrTypCd);
            typTmplMap.put("TRANS_MNRTYP_CD", transMnrTypCd);
            typTmplMap.put("TMP1", tmp1);
            typTmplMap.put("TMP2", tmp2);
            typTmplMap.put("TMP3", tmp3);
            typTmplMap.put("TMP4", tmp4);
            
            String string = CpfsFeAllConfig.jedisCluster.hmset(key, typTmplMap);
            
            TrcLog.log("redisTypTmpl.log", "key值："+key + "是否存入：" + string+"---存入内容："+typTmplMap.toString());
        }
    }
    
    
    
    
    /**
     * @author gongxb
     * 从缓存中读取类型模板配置
     */
    public static Map<String,String> readTypTmplFromRedis(String asscOEcd, String majTypCd, String mnrTypCd) {          
        String tmplKey = asscOEcd + "_" + majTypCd + "_" + mnrTypCd + "_TP_TYP_TMPL";
        TrcLog.log("readTypTmplFromRedis.log", tmplKey);
       
        Map<String,String> typTmpl = CpfsFeAllConfig.jedisCluster.hgetAll(tmplKey);
        boolean flag = typTmpl.isEmpty();
        String aa = "0";
        if(flag == true) {
            aa = "1";
        }
        
        TrcLog.log("readTypTmplFromRedis.log", aa);
        if (StringTool.isNullOrEmpty(typTmpl.get("MAJTYP_CD")) || StringTool.isNullOrEmpty(typTmpl.get("MNRTYP_CD")) ) {
            //RedisOper.putSrvRedis();
            //去公共体系查询模板表中是否存在记录--
            SvcDepend svcDepend = new SvcDepend();
            svcDepend.setSrcType("C");
            DtaInfo dtaInfo = DtaInfo.getInstance();
            String dtaNm = dtaInfo.getDtaName();
            String svcNm = dtaInfo.getSvcName();
            TrcLog.info("readTypTmplFromRedis.log", dtaNm + ":" + svcNm);
            svcDepend.setSrcName(dtaNm);
            svcDepend.setSrcSvcName(svcNm);
            String destType = "O";
            String destName = "c00_w01_output";
            String svcName = "iQ_TypTmpl";
            svcDepend.setDestType(destType);
            svcDepend.setDestName(destName);
            svcDepend.setSvcName(svcName);
            ConcurrentHashMap<String, SvcDepend> svcDependMap = PoolOperate.getResPoolByVersion(dtaInfo.getDepVersion())
                    .getAlaHashMap().get(dtaInfo.getDtaName()).getSvcDependMap();
            String key = dtaNm + svcNm + destName + svcName;
            if (svcDependMap.get(key) == null) {
                svcDependMap.put(key, svcDepend);
            }
            EPOper.put(dtaInfo.getTpId(), "ReqBean[0].head[0].servEcd[0]", "iQ_TypTmpl");
            
            EPOper.put(dtaInfo.getCpId(), "iQ_TypTmpl_REQ[0].asscOEcd[0]", asscOEcd);
            EPOper.put(dtaInfo.getCpId(), "iQ_TypTmpl_REQ[0].majTypCd[0]", majTypCd);
            EPOper.put(dtaInfo.getCpId(), "iQ_TypTmpl_REQ[0].mnrTypCd[0]", mnrTypCd);
            
            DTATool dtaTool = (DTATool) SpringUtil.getBean("dtaTool");
            dtaTool.callOutPut("c00_w01_output", "iQ_TypTmpl");
            TrcLog.info("readTypTmplFromRedis.log", "调用%s的%s","c00_w01_output","iQ_TypTmpl");
            
            TrcLog.info("readTypTmplFromRedis.log", typTmpl.toString()+"--");
            String respCode = (String) EPOper.get(dtaInfo.getCpId(), "RspBean[0].head[0].rspsCd[0]");
            TrcLog.info("readTypTmplFromRedis.log", "返回码%s",respCode);
            String transMnrTypCd = (String) EPOper.get(dtaInfo.getCpId(), "iQ_TypTmpl_RSP[0].transMnrTypCd[0]");
            String tmp1 = (String) EPOper.get(dtaInfo.getCpId(), "iQ_TypTmpl_RSP[0].tmp1[0]");
            String tmp2 = (String) EPOper.get(dtaInfo.getCpId(), "iQ_TypTmpl_RSP[0].tmp2[0]");
            String tmp3 = (String) EPOper.get(dtaInfo.getCpId(), "iQ_TypTmpl_RSP[0].tmp3[0]");
            String tmp4 = (String) EPOper.get(dtaInfo.getCpId(), "iQ_TypTmpl_RSP[0].tmp4[0]");
            
            
            TrcLog.info("readTypTmplFromRedis.log", "取服务返回转换后代码--%s tmp1--%s",transMnrTypCd,tmp1);
            if(respCode.equals("0000000")) {
                //有记录，存入redis
               
                typTmpl.put("ASSC_O_ECD", asscOEcd);
                typTmpl.put("MAJTYP_CD", majTypCd);
                typTmpl.put("MNRTYP_CD", mnrTypCd); 
                
                if(!StringTool.isNullOrEmpty(transMnrTypCd)) {
                    typTmpl.put("TRANS_MNRTYP_CD", transMnrTypCd);
                }
                if(!StringTool.isNullOrEmpty(tmp1)) {
                    typTmpl.put("TMP1", tmp1);
                }
                if(!StringTool.isNullOrEmpty(tmp2)) {
                    typTmpl.put("TMP2", tmp2);
                }
                if(!StringTool.isNullOrEmpty(tmp3)) {
                    typTmpl.put("TMP3", tmp3);
                }
                if(!StringTool.isNullOrEmpty(tmp4)) {
                    typTmpl.put("TMP4", tmp4);
                }
                
                String result = CpfsFeAllConfig.jedisCluster.hmset(tmplKey, typTmpl);
                TrcLog.log("readTypTmplFromRedis.log", "存入结果："+result);
            }
            
        }
        TrcLog.log("readTypTmplFromRedis.log", typTmpl.toString());
        return typTmpl;
        
    }
    /**
     * 新增模板获取序号
     * @return
     */
	public static String getIfmNo(){
		Long incrBy = CpfsFeAllConfig.jedisCluster.incrBy("IFM_NO", 1);
		return "A"+incrBy;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
